<template>
  <div>
    <!--<el-button type="primary" @click="startPosition()">获取当前定位</el-button>-->
    <el-button type="primary" @click="getVehicleListCU(false)">查询车辆</el-button>
    <div class="toolbar">{{ address }}</div>
    <hr />
    <div class="amap-page-container">
      <el-amap
        vid="amap"
        :zoom="zoom"
        class="my-vehicle-amap"
        :center="currentWindow.position"
        :amap-manager="amapManager"
        :events="events"
      >
        <template v-for="(mark,index) in marks">
          <el-amap-marker :position="mark.position" :events="mark.events">
            <div :class="`marker-vehicle ${mark.data.loadStatus==1?'online':'offline'}`" :style="`transform: rotate(${mark.data.direction}deg);`">
              <div class="marker-vehicle-icon" :style="`transform: rotate(${-mark.data.direction}deg);`"></div>
            </div>
          </el-amap-marker>
        </template>
        <el-amap-info-window
          :position="currentWindow.position"
          :visible="currentWindow.visible"
          :events="currentWindow.events">
          <div class="my-marker-title">{{currentWindow.data.vehicleNumber}}({{currentWindow.data.loadStatus==1?'在途':'空载'}})</div>
          <div class="my-marker-body">
            <div>上报时间：{{currentWindow.data.locationTime}}</div>
            <div>车速：西北{{currentWindow.data.speed}}km/h</div>
            <div>当前位置：{{currentWindow.data.locationAddress}}</div>
          </div>
          <div class="my-marker-foot">
            <el-button type="primary" size="mini" slot="append" icon="el-icon-location-information" @click="getMarkPath">轨迹</el-button>
          </div>
        </el-amap-info-window>
        <el-amap-bezier-curve
          v-for="line in lines"
          :key="line.id"
          :events="line.events"
          :path="line.path"
          :stroke-color="line.strokeColor"
          :stroke-style="line.strokeStyle"
          :stroke-opacity="line.strokeOpacity"
        ></el-amap-bezier-curve>
      </el-amap>
    </div>
    <el-drawer title="阿帕智运" :visible.sync="drawer" :with-header="false">
      <el-container style="height: 100%;">
        <el-header style="height: 135px;padding:15px 20px;">
          <el-row>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <p><i>线上车辆数</i></p>
                <p>
                  <i class="el-icon-s-data">{{allVehicle}}</i>
                </p>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple-light">
                <p><i>在途车辆数</i></p>
                <p>
                  <i class="el-icon-s-data">{{loadVehicle}}</i>
                </p>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-input placeholder="输入车牌号进行过滤" v-model="treeQueryText">
                <el-button :disabled="getVehicleListBtn" slot="append" icon="el-icon-refresh" @click="getVehicleListCU(true)">强制重新加载</el-button>
              </el-input>
            </el-col>
          </el-row>
        </el-header>
        <el-main style="height: 600px;padding:15px 20px;position: relative;">
          <el-button @click="getCheckedNodes" type="primary" icon="el-icon-position" style="position: absolute; top: 35px; right: 50px; z-index: 1;">查看位置</el-button>
          <!--default-expand-all-->
          <el-tree style="border: 1px solid #eee; border-radius: 4px;height: 100%; overflow: auto;"
            :data="vehicleList"
            show-checkbox
            ref="tree"
            highlight-current
            @check-change="handleCheckChange"
            node-key="id"
            :props="defaultProps"
            :filter-node-method="treefilterFunc"
          ></el-tree>
        </el-main>
      </el-container>
    </el-drawer>
  </div>
</template>
<script>
  import Vue from "vue";
  import { Script } from "vm";
  import { vehicleMap, vehicleTree } from "@/api/vehiclemap";
  import { AMapManager } from "vue-amap";
  import "@/assets/vehicle_map/icon.css";
  const amapManager = new AMapManager();
  export default {
    watch: {
      treeQueryText(val) {
        this.$refs.tree.filter(val);
      }
    },
    data() {
      const self = this;
      return {
        allVehicle:0,
        loadVehicle:0,
        treeQueryText: "",
        getVehicleListBtn:false,
        amapManager:amapManager,
        currentWindow: {
          position: [118.363007, 35.10964],
          data: {times:[]},
          events: {},
          visible: false
        },
        lines: [],
        zoom: 8,
        events: {
          init(o) {
            /*let marker = new AMap.Marker({
              position: [121.59996, 31.197646]
            });
            marker.setMap(o);*/
          }
        },
        marks: [],
        vehicleList: [],
        drawer: false,
        vehicleCodes: [],
        Selectarray: [],
        address: "",
        defaultProps: {
          children: "children",
          label: function(data,node){
            if(data.vehicleNumber){
              return data.vehicleNumber;
            }else{
              return data.teamName;
            }
          }
        }
      };
    },
    created() {
      //this.getVehicleList();
    },
    mounted() {

    },
    methods: {
      treefilterFunc(value, data) {
        if (!value) return true;
        if(data.vehicleNumber&&data.vehicleNumber.indexOf(value) !== -1){
          return true;
        }else{
          return false;
        }
      },
      getCheckedNodes() {
        this.currentWindow.visible = false;
        let Selection = this.$refs.tree.getCheckedNodes();
        if (Selection.length == 0) {
          this.$message({
            message: "请选择车辆！",
            type: "warning"
          });
        } else {
          this.Selectarray = [];
          this.vehicleCodes = [];
          Selection.map(item => {
            this.Selectarray.push(item.vehicleCode);
          });
          this.vehicleCodes = this.Selectarray.join(",");
          vehicleMap(this.vehicleCodes).then(response => {
            this.loadMark(response.data);
          });
        }
      },
      loadMark(list){
        this.marks.length=0;
        if(list&&list.length>0){
          let maxY,maxX,minY,minX;
          for(let i in list){
            let item = list[i],x=Number(item.longitude),y=Number(item.latitude);
            if(isNaN(x)||isNaN(y)){
              return true;
            }
            if(maxX===void 0){
              maxX = x,minX = x;
            }else if(x>maxX){
              maxX = x;
            }else if(x<minX){
              minX = x;
            }
            if(maxY===void 0){
              maxY = y,minY = y;
            }else if(y>maxY){
              maxY = y;
            }else if(y<minY){
              minY = y;
            }
            this.marks.push({
              position: [x,y],
              data: this.loadMarkData(item),
              visible: false,
              events: {
                click: () => {
                  this.switchWindow(i+'');
                }
              }
            });
          }
          let cz = this.getCenterPoint(maxX,minX,maxY,minY);
          this.currentWindow.position = [cz[0],cz[1]];
          this.zoom = cz[2];
        }
      },
      loadMarkData(item){
        let data = {};
        data.vehicleCode = item.vehicleCode;
        data.vehicleNumber = item.vehicleNumber;
        data.locationTime = item.locationTime;
        data.speed = item.speed;
        data.locationAddress = item.locationAddress;
        data.loadStatus = item.loadStatus;
        data.direction = item.direction?item.direction:0;
        data.times = [];
        return data;
      },
      switchWindow(tab) {
        if(tab===void 0){
          this.currentWindow.visible = false;
          this.$nextTick(() => {
            this.currentWindow.visible = true;
          });
        }else{
          this.currentWindow.visible = false;
          this.$nextTick(() => {
            this.currentWindow = this.marks[tab];
            this.currentWindow.visible = true;
          });
        }

      },
      getMarkPath(){
        window.open('/trackOfVehicle?vehicleCode='+this.currentWindow.data.vehicleCode+'&vehicleNumber='+this.currentWindow.data.vehicleNumber, '_blank');
      },
      loadLine(list){
        if(list&&list.length>0){
          let line = {
            path: [],
            strokeDasharray: [10, 10],
            strokeColor: "#3366FF", //线颜色
            strokeOpacity: 1, //线透明度
            strokeWeight: 6, //线宽
            strokeStyle: "solid", //线样式
            events: {
              click: () => {
                alert("click");
              }
            }
          };
          for(let i in list){
            line.path.push([list[i].longitude, list[i].latitude]);
          }
          this.lines.push(line);
        }else{
          this.$message({ message: '该时间范围内未查询到轨迹！', type: 'error' });
        }
      },
      //根据经纬度的距离获取地图的缩放级
      getCenterPoint(maxJ,minJ,maxW,minW){//通过经纬度获取中心位置和缩放级别
        if(maxJ==minJ&&maxW==minW)return [maxJ,maxW,12];
        var diff = maxJ - minJ;
        if(diff < (maxW - minW))diff = maxW - minW;
        diff = parseInt(10000 * diff)/10000;
        var centerJ = minJ*1000000+1000000*(maxJ - minJ)/2;
        var centerW = minW*1000000+1000000*(maxW - minW)/2;
        var zoom = this.getRoom(diff);
        return [centerJ/1000000,centerW/1000000,zoom];
      },
      getRoom(diff){
        let room = new Array(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14);
        let diffArr = new Array(360,180,90,45,22,11,5,2.5,1.25,0.6,0.3,0.15,0.07,0.03,0);
        for(let i = 0; i < diffArr.length; i ++){
          if((diff - diffArr[i]) >= 0){
            return room[i];
          }
        }
        return 14;
      },
      //货物车队信息
      getVehicleListCU(refresh) {//参数控制强制刷新
        this.drawer = true;
        if(this.getVehicleListBtn){//正在查询数据时自动跳过数据查询操作
          return;
        }
        if(!this.vehicleList||this.vehicleList.length==0||refresh){
          this.getVehicleList();
        }
      },
      getVehicleList(){
        this.getVehicleListBtn = true;
        vehicleTree().then(response => {
          this.vehicleList = response.data;
          this.countVehicle(response.data);
          this.getVehicleListBtn = false;
          this.treeQueryText = '';
        });
      },
      countVehicle(list){
        for(let i in list){
          let data = list[i];
          if(data.teamCode){
            this.countVehicle(data.children);
          }else{
            if(data.loadStatus==1){
              this.loadVehicle++;
            }
            this.allVehicle++;
          }
        }
      },
      handleCheckChange(data) {
        console.log(data);
      }
    }
  };
</script>
<style lang="scss" type="text/scss" scoped>
  .el-cascader-menu__wrap {
    height: 800px;
  }
  .amap-page-container {
    height: 800px;
  }
  .grid-content p {
    text-align: center;
    color: #606266;
  }
  .slotInfo-win{
    width: 200px;
    border-radius: 4px;
    padding: 2px 8px;
    background: #b2d8fb;
    color: #333;
    border: 1px solid #1890ff;
    font-weight: normal;
    button{
      border-radius: 4px;
    }
  }
  .slotInfo{
    width: 200px;
    border-radius: 4px;
    padding: 2px 8px;
    background: #b2d8fb;
    color: #333;
    border: 1px solid #1890ff;
    font-weight: normal;
    position: absolute;
    top: -32px;
    left: -82px;
    button{
      border-radius: 4px;
    }
  }


</style>
<style lang="scss" type="text/scss">
  .my-vehicle-amap{
    .amap-info-contentContainer{
      .amap-info-content{
        padding: unset;
        border-radius: 2px;
        font-size: 14px;
        width: 396px;
        .my-marker-title{
          color: #E5EBF0;
          padding: 4px 18px 2px 2px;
          background-color:#353B4A;
          border-radius: 2px 2px 0 0;
        }
        .my-marker-body{
          border-radius: 0 0 2px 2px;
          line-height: 1.8em;
          padding: 4px;
        }
        .my-marker-foot{
          background-color:#F5F6F7;
          padding: 4px;
        }
      }
      .amap-info-close{
        top:5px;
        color: #E5EBF0;
      }
      .amap-info-close:hover{
        color: #fff;
      }
    }
  }
  .el-date-editor.myDatePick{
    width:308px;
    padding: 3px 0 3px 3px;
    .el-range__close-icon{
      width:25px;
    }
  }
  .amap-marker-content{
    top: 2px;
    left: -14px;
  }
</style>
